﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    [DynamicApiController]
    public class EnterprisePermissionController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public EnterprisePermissionController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }


        /// <summary>
        /// 企业权限列表
        /// </summary>
        /// <param name="eid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid)
        {
            JArray data = GetEnterprisePermissionTree(eid, 0).Result;
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        [NonAction]
        public async Task<JArray> GetEnterprisePermissionTree(long eid, long bspmid)
        {
            JArray data = new();
            List<EnterprisePermission> enterprisepermissions = await db.Queryable<EnterprisePermission>().Where(d => d.Eid == eid && d.ParentId == bspmid).OrderBy(d => d.SortId, OrderByType.Asc).ToListAsync();
            if (enterprisepermissions != null && enterprisepermissions.Count > 0)
            {
                foreach (var enterprisepermission in enterprisepermissions)
                {
                    JObject jo_menu = JObject.FromObject(enterprisepermission);
                    jo_menu.Add("children", GetEnterprisePermissionTree(eid, enterprisepermission.Bspmid).Result);
                    data.Add(jo_menu);
                }
            }
            return data;
        }

        /// <summary>
        /// 根据子ID获取所有父ID
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetallparentbychildrenid([FromForm] long eid, [FromForm] long id)
        {
            await GetAllParent(eid, id);

            JObject data = new();
            enterprisepermissions.Reverse();
            data.Add("parent_enterprisepermissions", JArray.FromObject(enterprisepermissions));
            List<EnterprisePermission> children_enterprisepermissions = await db.Queryable<EnterprisePermission>().Where(d => d.Eid == eid && d.ParentId == id).ToListAsync();
            data.Add("children_enterprisepermissions", children_enterprisepermissions == null ? null : JArray.FromObject(children_enterprisepermissions));
            return new JsonResult(new { status = "success", message = "获取所有父类成功", code = 1, data });
        }

        private readonly List<EnterprisePermission> enterprisepermissions = new(); // 所有企业权限父企业权限
        [NonAction]
        public async Task GetAllParent(long eid, long id)
        {
            // 查询当前节点信息
            EnterprisePermission enterprisepermission = await db.Queryable<EnterprisePermission>().Where(d => d.Eid == eid && d.Id == id).SingleAsync();
            if (enterprisepermission != null)
            {
                enterprisepermissions.Add(enterprisepermission);
                await GetAllParent(eid, enterprisepermission.ParentId);
            }
        }

        /// <summary>
        /// 异步获取子企业权限
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetchildren([FromForm] long eid, [FromForm] long parent_id)
        {
            List<EnterprisePermission> enterprisepermissions = await db.Queryable<EnterprisePermission>().Where(d => d.Eid == eid && d.ParentId == parent_id).OrderBy("sort_id asc").ToListAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = enterprisepermissions,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 企业权限增加
        /// </summary>
        /// <param name="strjsonenterprisepermissions"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] string strjsonenterprisepermissions)
        {
            List<EnterprisePermission> enterprisepermissions = JsonConvert.DeserializeObject<List<EnterprisePermission>>(strjsonenterprisepermissions);
            // 根据索引排序
            enterprisepermissions.ForEach(d => d.SortId = enterprisepermissions.IndexOf(d) + 1);
            List<EnterprisePermission> insertEnterprisePermissions = new();
            List<EnterprisePermission> updateEnterprisePermissions = new();
            foreach (var enterprisepermission in enterprisepermissions)
            {
                if (enterprisepermission.Id == 0)
                {
                    // 增加
                    insertEnterprisePermissions.Add(enterprisepermission);
                }
                else
                {
                    // 更新
                    updateEnterprisePermissions.Add(enterprisepermission);
                }
            }
            insertEnterprisePermissions.ForEach(idp => Console.WriteLine(idp.ToString()));
            updateEnterprisePermissions.ForEach(udp => Console.WriteLine("update" + udp.ToString()));
            JObject data = new();
            if (insertEnterprisePermissions.Count > 0)
            {
                // 执行插入操作
                int insertAffrows = await db.Insertable<EnterprisePermission>(insertEnterprisePermissions).ExecuteCommandAsync();
                data.Add("insertAffrows", insertAffrows);
            }
            if (updateEnterprisePermissions.Count > 0)
            {
                // 执行更新操作
                int updateAffrows = await db.Insertable<EnterprisePermission>(updateEnterprisePermissions).ExecuteCommandAsync();
                data.Add("updateAffrows", updateAffrows);
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id)
        {
            // 该企业权限下有子企业权限不让删除
            EnterprisePermission enterprisepermission = await db.Queryable<EnterprisePermission>().Where(d => d.Eid == eid && d.ParentId == id).SingleAsync();
            if (enterprisepermission != null)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该企业权限下拥有子企业权限，不允许删除",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            int affrows = await db.Deleteable<EnterprisePermission>().Where(d => d.Eid == eid && d.Id == id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = -1,
                Succeeded = false,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="enterprisepermission"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] EnterprisePermission enterprisepermission)
        {
            int affrows = await db.Updateable<EnterprisePermission>(enterprisepermission).Where(d => d.Eid == eid).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 企业权限查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            EnterprisePermission enterprisepermission = await db.Queryable<EnterprisePermission>().Where(d => d.Eid == eid && d.Id == id).SingleAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = enterprisepermission,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 拖拽
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="strjsonenterprisepermissions"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDrag([FromForm] long eid, [FromForm] string strjsonenterprisepermissions)
        {
            List<EnterprisePermission> enterprisepermissions = JsonConvert.DeserializeObject<List<EnterprisePermission>>(strjsonenterprisepermissions);
            enterprisepermissions.ForEach(d => d.SortId = enterprisepermissions.IndexOf(d) + 1);
            int affrows = await db.Updateable<EnterprisePermission>(enterprisepermissions).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = "拖拽更新成功",
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
